package eu.telecom_bretagne.RECRUT.servlet;

import java.io.IOException;
import java.sql.Date;
import java.util.GregorianCalendar;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.telecom_bretagne.RECRUT.service.IServiceEntretien;

/**
 * Servlet implementation class ModificationEntretien
 */
@WebServlet("/modifier_entretien")
public class ModificationEntretien extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ModificationEntretien() {
		super();
	}

	public final static Date convertNumericToDate(Integer dateNumeric) {
		GregorianCalendar calendar = new GregorianCalendar();
		Date date = null;
		// Si la date est au bon format
		if (dateNumeric != null && dateNumeric != 0
				&& dateNumeric.toString().length() == 8) {
			String dateString = dateNumeric.toString();
			calendar.clear();
			calendar.set(Integer.parseInt(dateString.substring(0, 4)),
					Integer.parseInt(dateString.substring(4, 6)),
					Integer.parseInt(dateString.substring(6, 8)));
			date = new Date(calendar.getTimeInMillis());
		}
		return date;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String idT = request.getParameter("date");

		try {
			int nouvelleDate = Integer.parseInt(idT);
			InitialContext ctx = new InitialContext();
			IServiceEntretien serviceEntretien = (IServiceEntretien) ctx
					.lookup(IServiceEntretien.JNDI_NAME);
			serviceEntretien.modifierEntretien(Integer.parseInt(id),
					convertNumericToDate(nouvelleDate));
			;
		} catch (NamingException e) {
			throw new ServletException(e);
		}
		response.sendRedirect("index.jsp");
	}

}
